/**
 * 根据经纬度计算距离
 * @param {number} lat1
 * @param {number} lon1
 * @param {number} lat2
 * @param {number} lon2
 * @returns {number} 返回单位为千米的距离
 */
export function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number) {
	// 将角度转换为弧度
	lat1 = (lat1 * Math.PI) / 180;
	lon1 = (lon1 * Math.PI) / 180;
	lat2 = (lat2 * Math.PI) / 180;
	lon2 = (lon2 * Math.PI) / 180;

	// 计算纬度和经度的差值
	const dLat = lat2 - lat1;
	const dLon = lon2 - lon1;

	// 应用Haversine公式
	const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

	// 地球半径，单位：千米
	const r = 6371;

	// 计算距离
	const distance = r * c;

	return distance;
}
